<!-- 引导覆盖层组件 -->
<template>
	<view v-if="modelValue" class="guide-container">
		<!-- 蒙版层 -->
		<view class="guide-mask" @click="clickMask"></view>
		
		<!-- 引导高亮元素 -->
		<view v-if="targetRect" class="guide-highlight" :style="highlightStyle"></view>
		
		<!-- 提示气泡 -->
		<view v-if="targetRect" class="guide-bubble" :style="popoverStyle">
			<view class="guide-title" v-if="currentStepConfig.title">{{ currentStepConfig.title }}</view>
			<view class="guide-description">{{ currentStepConfig.content || currentStepConfig.description }}</view>
		</view>
		
		<!-- 控制按钮 - 完全独立的层 -->
		<view class="guide-controls">
			<view class="guide-dots">
				<view 
					v-for="(_, index) in steps" 
					:key="index"
					class="guide-dot"
					:class="{ active: currentStep === index }"
				></view>
			</view>
			
			<view class="guide-buttons">
				<view 
					v-if="showSkip && currentStep < steps.length - 1" 
					class="guide-btn guide-skip-btn" 
					@tap="onSkip"
				>跳过</view>
				
				<view class="guide-nav-buttons">
					<view 
						v-if="currentStep > 0" 
						class="guide-btn guide-prev-btn" 
						@tap="prevStep"
					>上一步</view>
					
					<view 
						v-if="currentStep < steps.length - 1" 
						class="guide-btn guide-next-btn" 
						@tap="nextStep"
					>下一步</view>
					
					<view 
						v-else 
						class="guide-btn guide-finish-btn" 
						@tap="finish"
					>完成</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
import { ref, onMounted, watch, computed, nextTick, onUnmounted } from 'vue';

export default {
	name: 'GuideOverlay',
	props: {
		// 控制指南是否显示
		modelValue: {
			type: Boolean,
			default: false
		},
		// 当前步骤
		step: {
			type: Number,
			default: 0
		},
		// 引导步骤配置
		steps: {
			type: Array,
			default: () => []
		},
		// 点击遮罩是否关闭
		closeOnClickMask: {
			type: Boolean,
			default: false
		},
		// 是否显示跳过按钮
		showSkip: {
			type: Boolean,
			default: true
		},
		// 指南层级
		zIndex: {
			type: Number,
			default: 10000
		},
		// 本地存储键名，用于记录引导完成状态 生产环境
		storageKey: {
			type: String,
			default: 'guide_completed'
		},
		// 是否自动检查本地存储状态
		checkStorage: {
			type: Boolean,
			default: true
		},
		// 高亮框样式
		highlightStyle: {
			type: Object,
			default: () => ({
				borderColor: '#6A75FE',
				borderWidth: '3px',
				borderStyle: 'solid',
				backgroundColor: 'rgba(255, 255, 255, 0.1)',
				shadowColor: 'rgba(0, 0, 0, 0.6)'
			})
		},
		// 气泡框样式
		bubbleStyle: {
			type: Object,
			default: () => ({
				backgroundColor: '#fff',
				textColor: '#666',
				titleColor: '#333',
				boxShadow: '0 4px 12px rgba(0, 0, 0, 0.15)'
			})
		},
		// 气泡框与高亮框的间距
		bubbleOffset: {
			type: Number,
			default: 25
		}
	},
	emits: ['update:modelValue', 'update:step', 'finish', 'skip', 'next', 'prev', 'change'],
	setup(props, { emit }) {
		console.log('[Guide] 初始化引导组件');
		
		// 使用简单的内部状态而不是复杂的计算属性
		const innerStep = ref(props.step);
		const isChanging = ref(false);
		const targetRect = ref(null);
		const windowInfo = ref(null);
		
		// 获取当前步骤配置 - 简单函数，不使用计算属性
		const getCurrentStep = () => {
			const stepIndex = innerStep.value;
			if (stepIndex >= 0 && stepIndex < props.steps.length) {
				return props.steps[stepIndex];
			}
			return null;
		};
		
		// 同步外部和内部步骤
		watch(() => props.step, (newVal) => {
			console.log(`[Guide] 外部步骤变化: ${innerStep.value} -> ${newVal}`);
			if (newVal !== innerStep.value && !isChanging.value) {
				// 更新内部步骤
				changeStep(newVal);
			}
		});
		
		// 获取窗口信息
		const getWindowInfo = () => {
			try {
				const info = uni.getSystemInfoSync();
				windowInfo.value = info;
			} catch (e) {
				console.error('[Guide] 获取窗口信息失败:', e);
			}
		};
		
		// 清除元素位置
		const clearTarget = () => {
			targetRect.value = null;
		};
		
		// 统一的步骤切换函数
		const changeStep = (newStep) => {
			if (isChanging.value) {
				console.log('[Guide] 忽略重复的步骤切换请求');
				return;
			}
			
			if (newStep < 0 || newStep >= props.steps.length) {
				console.log(`[Guide] 步骤超出范围: ${newStep}, 总步骤: ${props.steps.length}`);
				return;
			}
			
			console.log(`[Guide] 切换步骤: ${innerStep.value} -> ${newStep}`);
			
			// 设置切换状态
			isChanging.value = true;
			
			// 1. 清除旧的元素位置
			clearTarget();
			
			// 2. 更新内部步骤
			innerStep.value = newStep;
			
			// 3. 通知外部更新
			emit('update:step', newStep);
			emit('change', newStep);
			
			// 4. 查找新步骤的元素
			setTimeout(() => {
				findTargetElement();
				
				// 5. 重置切换状态
				setTimeout(() => {
					isChanging.value = false;
				}, 100);
			}, 300);
		};
		
		// 下一步函数
		const nextStep = () => {
			console.log('[Guide] 点击下一步按钮');
			const next = innerStep.value + 1;
			
			if (next >= props.steps.length) {
				// 已经是最后一步
				emit('update:modelValue', false);
				emit('finish');
				return;
			}
			
			// 通知将要前进
			emit('next', innerStep.value);
			
			// 切换到下一步
			changeStep(next);
		};
		
		// 上一步函数
		const prevStep = () => {
			console.log('[Guide] 点击上一步按钮');
			const prev = innerStep.value - 1;
			
			if (prev < 0) {
				// 已经是第一步
				return;
			}
			
			// 通知将要后退
			emit('prev', innerStep.value);
			
			// 切换到上一步
			changeStep(prev);
		};
		
		// 完成引导
		const finish = () => {
			console.log('[Guide] 完成引导');
			// 保存完成状态到本地存储
			if (props.storageKey) {
				uni.setStorageSync(props.storageKey, true);
				console.log(`[Guide] 已保存完成状态到本地: ${props.storageKey}`);
			}
			emit('update:modelValue', false);
			emit('finish');
		};
		
		// 跳过引导
		const onSkip = () => {
			console.log('[Guide] 跳过引导');
			// 保存完成状态到本地存储
			if (props.storageKey) {
				uni.setStorageSync(props.storageKey, true);
				console.log(`[Guide] 已保存跳过状态到本地: ${props.storageKey}`);
			}
			emit('update:modelValue', false);
			emit('skip');
		};
		
		// 点击遮罩
		const clickMask = () => {
			if (props.closeOnClickMask) {
				emit('update:modelValue', false);
			}
		};
		
		// 查找目标元素 - 简化的逻辑
		const findTargetElement = async () => {
			// 获取当前步骤配置
			const stepConfig = getCurrentStep();
			
			if (!stepConfig || !stepConfig.selector) {
				console.error('[Guide] 当前步骤无有效选择器');
				return;
			}
			
			const selector = stepConfig.selector;
			const currentStepIndex = innerStep.value;
			
			console.log(`[Guide] 查找步骤 ${currentStepIndex} 的元素, 选择器: ${selector}`);
			
			// 确保DOM更新完成
			await nextTick();
			
			try {
				// 使用Promise包装查询操作
				const findElement = () => {
					return new Promise((resolve) => {
						const query = uni.createSelectorQuery();
						
						// 先尝试直接查询
						query.select(selector).boundingClientRect(rect => {
							if (rect && rect.width > 0 && rect.height > 0) {
								console.log(`[Guide] 找到元素:`, rect);
								resolve(rect);
							} else {
								// 如果找不到，尝试查询所有匹配元素
								console.log(`[Guide] 未找到单个元素，尝试查询所有`);
								const allQuery = uni.createSelectorQuery();
								allQuery.selectAll(selector).boundingClientRect(rects => {
									if (rects && rects.length > 0 && rects[0].width > 0 && rects[0].height > 0) {
										console.log(`[Guide] 找到多个元素，使用第一个:`, rects[0]);
										resolve(rects[0]);
									} else {
										console.error(`[Guide] 无法找到元素: ${selector}`);
										resolve(null);
									}
								}).exec();
							}
						}).exec();
					});
				};
				
				// 尝试多次查找元素
				const tryFind = async (attempts = 3, delay = 300) => {
					for (let i = 0; i < attempts; i++) {
						// 确保步骤没有变化
						if (innerStep.value !== currentStepIndex) {
							console.log(`[Guide] 步骤已变化，停止查找`);
							return;
						}
						
						console.log(`[Guide] 查找元素尝试 ${i+1}/${attempts}`);
						const found = await findElement();
						
						if (found) {
							// 只在步骤没变的情况下更新
							if (innerStep.value === currentStepIndex) {
								targetRect.value = found;
							}
							return;
						}
						
						// 延迟后再次尝试
						if (i < attempts - 1) {
							await new Promise(resolve => setTimeout(resolve, delay));
						}
					}
					
					console.error(`[Guide] 经过多次尝试，仍无法找到元素: ${selector}`);
				};
				
				// 延迟调用，确保DOM已更新
				setTimeout(() => {
					tryFind();
				}, 300);
				
			} catch (error) {
				console.error('[Guide] 查找元素错误:', error);
			}
		};
		
		// 高亮区域样式
		const highlightStyle = computed(() => {
			if (!targetRect.value) {
				return { display: 'none' };
			}
			
			const currentStep = getCurrentStep();
			const padding = currentStep?.padding || 10;
			const customStyle = props.highlightStyle;
			
			return {
				top: `${targetRect.value.top - padding}px`,
				left: `${targetRect.value.left - padding}px`,
				width: `${targetRect.value.width + padding * 2}px`,
				height: `${targetRect.value.height + padding * 2}px`,
				zIndex: props.zIndex + 2,
				border: `${customStyle.borderWidth} ${customStyle.borderStyle} ${customStyle.borderColor}`,
				backgroundColor: customStyle.backgroundColor,
				boxShadow: `0 0 0 9999px ${customStyle.shadowColor}`
			};
		});
		
		// 气泡样式
		const popoverStyle = computed(() => {
			if (!targetRect.value || !windowInfo.value) {
				return { display: 'none' };
			}
			
			const currentStep = getCurrentStep();
			const screenWidth = windowInfo.value.windowWidth || 375;
			const screenHeight = windowInfo.value.windowHeight || 667;
			const bubbleWidth = 220;
			const bubbleHeight = 100;
			const margin = 20;
			const offset = props.bubbleOffset;
			
			const rect = targetRect.value;
			let position = currentStep?.position || 'bottom';
			
			// 基础样式
			const style = { 
				zIndex: props.zIndex + 3,
				width: `${bubbleWidth}px`,
				maxWidth: '80%',
				backgroundColor: props.bubbleStyle.backgroundColor,
				boxShadow: props.bubbleStyle.boxShadow,
				color: props.bubbleStyle.textColor,
				backdropFilter: 'blur(8px)',
				WebkitBackdropFilter: 'blur(8px)'
			};
			
			// 计算各个方向的溢出量
			const overflow = {
				top: rect.top < bubbleHeight + margin,
				bottom: rect.top + rect.height + bubbleHeight + margin > screenHeight,
				left: rect.left < bubbleWidth + margin,
				right: rect.left + rect.width + bubbleWidth + margin > screenWidth
			};
			
			// 根据溢出情况调整位置
			switch (position) {
				case 'top':
					if (overflow.top) {
						position = 'bottom';
					}
					break;
				case 'bottom':
					if (overflow.bottom) {
						position = 'top';
					}
					break;
				case 'left':
					if (overflow.left) {
						position = 'right';
					}
					break;
				case 'right':
					if (overflow.right) {
						position = 'left';
					}
					break;
			}
			
			// 计算基础位置
			let left = 0;
			let top = 0;
			
			switch (position) {
				case 'top':
					// 水平居中
					left = rect.left + (rect.width - bubbleWidth) / 2;
					top = rect.top - bubbleHeight - offset;
					break;
					
				case 'bottom':
					// 水平居中
					left = rect.left + (rect.width - bubbleWidth) / 2;
					top = rect.top + rect.height + offset;
					break;
					
				case 'left':
					// 垂直居中
					left = rect.left - bubbleWidth - offset;
					top = rect.top + (rect.height - bubbleHeight) / 2;
					break;
					
				case 'right':
					// 垂直居中
					left = rect.left + rect.width + offset;
					top = rect.top + (rect.height - bubbleHeight) / 2;
					break;
			}
			
			// 防止水平溢出
			if (left < margin) {
				left = margin;
			} else if (left + bubbleWidth > screenWidth - margin) {
				left = screenWidth - bubbleWidth - margin;
			}
			
			// 防止垂直溢出
			if (top < margin) {
				top = margin;
			} else if (top + bubbleHeight > screenHeight - margin) {
				top = screenHeight - bubbleHeight - margin;
			}
			
			// 设置最终位置
			style.left = `${left}px`;
			style.top = `${top}px`;
			
			// 添加气泡方向的class
			style.class = `guide-bubble-${position}`;
			
			return style;
		});
		
		// 监听显示状态
		watch(() => props.modelValue, (val) => {
			console.log('[Guide] 显示状态变化:', val);
			if (val) {
				// 初始化
				getWindowInfo();
				innerStep.value = props.step;
				findTargetElement();
			} else {
				// 清理
				clearTarget();
			}
		});
		
		// 组件初始化
		onMounted(() => {
			// 检查本地存储，如果已完成则不显示引导
			if (props.modelValue && checkGuideStatus()) {
				console.log('[Guide] 用户已完成引导，不显示');
				emit('update:modelValue', false);
				return;
			}
			
			if (props.modelValue) {
				getWindowInfo();
				findTargetElement();
			}
		});
		
		// 暴露当前步骤配置给模板
		const currentStepConfig = computed(() => {
			return getCurrentStep() || {};
		});
		
		// 添加重置引导状态的方法
		const resetGuideStatus = () => {
			console.log('[Guide] 重置引导状态');
			if (props.storageKey) {
				uni.removeStorageSync(props.storageKey);
				console.log(`[Guide] 已删除本地存储的引导状态: ${props.storageKey}`);
			}
		};
		
		// 检查本地存储，如果已完成则不显示引导
		const checkGuideStatus = () => {
			if (props.checkStorage && props.storageKey) {
				const completed = uni.getStorageSync(props.storageKey);
				if (completed) {
					console.log(`[Guide] 检测到用户已完成引导: ${props.storageKey}`);
					return true;
				}
			}
			return false;
		};
		
		return {
			innerStep,
			currentStepConfig,
			targetRect,
			highlightStyle,
			popoverStyle,
			nextStep,
			prevStep,
			finish,
			onSkip,
			clickMask,
			resetGuideStatus,
			checkGuideStatus,
			
			// 为了兼容模板，使用同名变量
			currentStep: innerStep
		};
	}
};
</script>

<style>
/* 引导容器 */
.guide-container {
	position: fixed;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	z-index: 10000;
}

/* 蒙版 */
.guide-mask {
	position: absolute;
	top: 0;
	left: 0;
	width: 100%;
	height: 100%;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 10001;
}

/* 高亮区域 */
.guide-highlight {
	position: absolute;
	border: 3px solid #6A75FE;
	background-color: rgba(255, 255, 255, 0.1);
	box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.6);
	border-radius: 4px;
	z-index: 10002;
	pointer-events: none;
	animation: pulse 2s infinite;
}

@keyframes pulse {
	0% { box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.6); }
	50% { box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.7); }
	100% { box-shadow: 0 0 0 9999px rgba(0, 0, 0, 0.6); }
}

/* 提示气泡 */
.guide-bubble {
	position: absolute;
	padding: 12px 16px;
	border-radius: 8px;
	box-sizing: border-box;
	z-index: 10003;
	animation: fadeIn 0.3s ease;
	font-size: 14px;
	line-height: 1.4;
	
	&::before {
		content: '';
		position: absolute;
		width: 0;
		height: 0;
		border: 6px solid transparent;
	}
	
	&.guide-bubble-top::before {
		bottom: -12px;
		left: 50%;
		transform: translateX(-50%);
		border-top-color: currentColor;
	}
	
	&.guide-bubble-right::before {
		left: -12px;
		top: 50%;
		transform: translateY(-50%);
		border-right-color: currentColor;
	}
	
	&.guide-bubble-bottom::before {
		top: -12px;
		left: 50%;
		transform: translateX(-50%);
		border-bottom-color: currentColor;
	}
	
	&.guide-bubble-left::before {
		right: -12px;
		top: 50%;
		transform: translateY(-50%);
		border-left-color: currentColor;
	}
}

@keyframes fadeIn {
	from { 
		opacity: 0; 
		transform: scale(0.95);
	}
	to { 
		opacity: 1; 
		transform: scale(1);
	}
}

.guide-title {
	font-size: 15px;
	font-weight: bold;
	margin-bottom: 6px;
}

.guide-description {
	font-size: 13px;
	line-height: 1.4;
	opacity: 0.9;
}

/* 控制按钮区域 */
.guide-controls {
	position: fixed;
	left: 0;
	right: 0;
	bottom: 50px;
	z-index: 10004;
	display: flex;
	flex-direction: column;
	align-items: center;
}

.guide-dots {
	display: flex;
	justify-content: center;
	margin-bottom: 20px;
}

.guide-dot {
	width: 16rpx;
	height: 16rpx;
	border-radius: 50%;
	background-color: rgba(255, 255, 255, 0.5);
	margin: 0 10rpx;
	transition: all 0.3s;
}

.guide-dot.active {
	background-color: #fff;
	transform: scale(1.3);
}

.guide-buttons {
	width: 100%;
	padding: 0 40rpx;
	box-sizing: border-box;
	position: relative;
}

.guide-nav-buttons {
	display: flex;
	justify-content: center;
	gap: 30rpx;
}

.guide-btn {
	padding: 20rpx 40rpx;
	background-color: rgba(255, 255, 255, 0.9);
	color: #333;
	border-radius: 100rpx;
	font-size: 28rpx;
	text-align: center;
	box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
	transition: all 0.2s;
}

.guide-btn:active {
	transform: scale(0.96);
	opacity: 0.9;
}

.guide-next-btn,
.guide-finish-btn {
	background-color: #409EFF;
	color: white;
}

.guide-skip-btn {
	position: absolute;
	top: -80rpx;
	right: 40rpx;
	padding: 10rpx 20rpx;
	background: none;
	font-size: 24rpx;
	color: rgba(255, 255, 255, 0.8);
	box-shadow: none;
}

/* 移除毛玻璃效果的强制背景色 */
@supports ((-webkit-backdrop-filter: none) or (backdrop-filter: none)) {
	.guide-bubble {
		backdrop-filter: blur(8px);
		-webkit-backdrop-filter: blur(8px);
	}
}
</style> 